<?php

namespace app\uniapp\controller;

use app\common\exception\MiException;
use app\model\store\GoodsReply;
use app\uniapp\middleware\CheckLogin;
use app\uniapp\service\GoodsReplyService;
use app\uniapp\service\OrderService;
use app\uniapp\service\UniAuthService;
use think\facade\Db;
use think\Request;
use think\response\Json;

class GoodsReplyController extends UniController
{

    protected array $middleware = [
        CheckLogin::class,
    ];

    /***
     * 通过订单添加商品评论
     * @param Request $request
     * @return Json|void
     */
    public function addByOrder(Request $request){
        if ($request->isPost()){

            Db::transaction(function () {
                $post = $this->post();
                $orderId = $post[0]['order_id'];
                // 查询订单是否已经评价
                $reply = GoodsReply::find($orderId);
                if ($reply){
                    throw new MiException("订单已评价");
                }
                foreach ($post as $v){
                    $v['user_id'] = UniAuthService::instance()->getLoginId();
                    $v['content'] = $v['content']??'';
                    $v['imageArr'] = $v['imageArr']??[];
                    GoodsReplyService::instance()->create($v);
                }
                // 修改订单状态为已完成
                OrderService::instance()->update(['order_status'=>'done'], ['id' => $orderId]);
            });

            return jsonSuccess();
        }
    }

    public function find(){

    }

    public function paginate(){

    }
}
